<template>
  <div>
    <el-drawer v-model="dialogVisible" :title="title" size="50%">
      <el-form ref="ruleFormRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="菜单类型" @change="menuTypeChange" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio-button value="CATALOG" :disabled="form.id && form.type !== 'CATALOG'">目录</el-radio-button>
            <el-radio-button value="MENU" :disabled="form.id && form.type !== 'MENU'">菜单</el-radio-button>
            <el-radio-button value="BUTTON" :disabled="form.id && form.type !== 'BUTTON'">按钮</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="menuTypeName" prop="name">
          <el-input v-model="form.name" placeholder="请输入菜单名称" />
        </el-form-item>
        <el-form-item label="父级菜单" prop="parentId">
          <el-tree-select
            v-model="form.parentId"
            :data="menuOptions"
            :props="{ value: 'id', label: 'name', children: 'children' }"
            value-key="id"
            placeholder="选择上级菜单"
            check-strictly
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="菜单图标" v-if="form.type !== 'BUTTON'">
          <el-popover
            placement="bottom-start"
            :width="540"
            trigger="click"
          >
            <template #reference>
              <el-input v-model="form.icon" placeholder="点击选择图标" @blur="showSelectIcon" readonly>
                <template #prefix>
                  <svg-icon
                    v-if="form.icon"
                    :icon-class="form.icon"
                    class="el-input__icon"
                    style="height: 32px;width: 16px;"
                  />
                  <el-icon v-else style="height: 32px;width: 16px;"><search /></el-icon>
                </template>
              </el-input>
            </template>
            <icon-select ref="iconSelectRef" @selected="selected" :active-icon="form.icon" />
          </el-popover>
        </el-form-item>
        <el-form-item label="权限标识" prop="perm" v-if="form.type !== 'CATALOG'">
          <el-input v-model="form.perm" placeholder="请输入权限标识" />
        </el-form-item>
        <el-form-item label="路由地址" prop="path"  v-if="form.type === 'MENU' || form.type === 'CATALOG'">
          <el-input v-model="form.path" placeholder="请输入路由地址" />
        </el-form-item>
        <el-form-item label="组件路径" prop="component" v-if="form.type === 'MENU'">
          <el-input v-model="form.component" placeholder="请输入组件路径(目录为Layout，菜单为组件views下地址路径)" />
        </el-form-item>
        <el-form-item label="显示排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" :max="999" controls-position="right" />
        </el-form-item>
        <el-form-item label="菜单状态" prop="status" v-if="form.type !== 'BUTTON'">
          <el-radio-group v-model="form.status">
            <el-radio :value="1">显示</el-radio>
            <el-radio :value="0">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否缓存" prop="keepAlive" v-if="form.type === 'MENU'">
          <el-radio-group v-model="form.keepAlive">
            <el-radio :value="1">缓存</el-radio>
            <el-radio :value="0">不缓存</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">确定</el-button>
        </span>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { FormInstance, ElMessage } from 'element-plus'
import { addMenu, updateMenu, listMenu } from '@/api/menus'
import IconSelect from "@/components/IconSelect";
interface MenuForm {
  id?: number
  parentId: number
  name: string
  type: 'CATALOG' | 'MENU' | 'BUTTON'
  path: string
  component: string
  perm: string
  icon: string
  sort: number
  keepAlive: 0 | 1
  status: 0 | 1
}

const emit = defineEmits(['success'])
const menuTypeName = ref('目录名称')
// 表单ref
const ruleFormRef = ref<FormInstance>()
// 抽屉显示
const dialogVisible = ref(false)
// 标题
const title = ref('新增菜单')
// 提交loading
const submitLoading = ref(false)
// 菜单树选项
const menuOptions = ref([])
// 下拉图标
const iconSelectRef = ref(null);
// 表单数据
const form = reactive<MenuForm>({
  parentId: 0,
  name: '',
  type: 'CATALOG',
  path: '',
  component: '',
  perm: '',
  icon: '',
  sort: 0,
  keepAlive: 0,
  status: 1
})

// 校验规则
const rules = reactive({
  name: [{ required: true, message: "菜单名称不能为空", trigger: "blur" }],
  type: [{ required: true, message: "菜单类型不能为空", trigger: "change" }],
  sort: [{ required: true, message: "排序不能为空", trigger: "blur" }],
  path: [{ required: true, message: "路由地址不能为空", trigger: "blur" }],
  component: [{ required: true, message: "组件路径不能为空", trigger: "blur" }]
})

/** 展示下拉图标 */
function showSelectIcon() {
  iconSelectRef.value.reset();
}

/** 选择图标 */
function selected(name) {
  form.icon = name;
}

/** 获取菜单树选项 */
const getTreeSelect = async () => {
  try {
    const res = await listMenu()
    menuOptions.value = [{ id: 0, name: '主目录', children: res.data }]
  } catch (error: any) {
    console.error('获取菜单树失败:', error)
    ElMessage.error(error.msg || '获取菜单树失败')
  }
}

/** 取消操作 */
const cancel = () => {
  resetForm()
  dialogVisible.value = false
}
/** 菜单类型改变 */
const menuTypeChange = (event: Event) => {

  const value = event.target?._value
  console.log(value);
  switch (value) {
    case 'CATALOG':
      menuTypeName.value = '目录名称'
      break
    case 'MENU':
      menuTypeName.value = '菜单名称'
      break
    case 'BUTTON':
      menuTypeName.value = '按钮名称'
      break
  }
}
/** 表单重置 */
const resetForm = () => {
  submitLoading.value = false
  ruleFormRef.value?.resetFields()
  Object.assign(form, {
    id: undefined,
    parentId: 0,
    name: '',
    type: 'CATALOG',
    path: '',
    component: '',
    perm: '',
    icon: '',
    sort: 0,
    keepAlive: 0,
    status: 1
  })
}

/** 表单提交 */
const submitForm = async () => {
  if (!ruleFormRef.value) return

  await ruleFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      submitLoading.value = true
      try {
        if (form.id) {
          delete form.children
          console.log(form);
          await updateMenu(form)
          ElMessage.success("修改成功")
        } else {
          await addMenu(form)
          ElMessage.success("新增成功")
        }
        dialogVisible.value = false
        emit('success')
      } catch (error: any) {
        ElMessage.error(error.msg || '操作失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

/** 显示弹框 */
const show = async (row?: Partial<MenuForm>) => {
  await getTreeSelect()

  if (row?.id) {
    title.value = "修改菜单"
    Object.assign(form, row)
  } else {
    title.value = "新增菜单"
    resetForm()
    if (row) {
      form.parentId = row.id!
    }
  }

  dialogVisible.value = true
}

defineExpose({
  show
})
</script>

<style scoped>
.dialog-footer {
  padding: 20px 0;
}
</style>
